package org.amicofragile.test.springintegration.transformation;

import java.text.MessageFormat;
import java.util.Date;

import org.amicofragile.test.springintegration.dto.Person;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.annotation.Transformer;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;

public class PersonToMailTransformer
{
	private static final String MESSAGE_BODY_TEMPLATE = "Complimenti, {0} {1}!\nQualcuno ti ha inviato i suoi saluti alle {3, date, HH:mm:ss} del {3, date, dd/MM/yyyy}!\nIl tuo indirizzo email è: {2}";

	private static final Log LOG = LogFactory.getLog(PersonToMailTransformer.class);

	private final String from;

	private final String subject;

	public PersonToMailTransformer(String from, String subject)
	{
		this.from = from;
		this.subject = subject;
	}

	@Transformer
	public MailMessage transform(final Person person)
	{
		final MailMessage msg = new SimpleMailMessage();
		final String to = (person.getName().charAt(0) + "." + person.getSurname()).toLowerCase() + "@trend.it";
		msg.setTo(to);
		msg.setFrom(from);
		final Date now = new Date();
		msg.setSentDate(now);
		msg.setSubject(subject);
		msg.setText(MessageFormat.format(MESSAGE_BODY_TEMPLATE, person.getName(), person.getSurname(), to, now));
		if (LOG.isInfoEnabled())
		{
			LOG.info("Creating MailMessage for recipient <" + to + ">");
		}
		return msg;
	}
}
